package com.smp.util;

import com.smp.enums.ExpoErrorCodeEnum;
import com.smp.exception.ExpoAppException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Describe class function detail.
 *
 * @author Yang.Yi
 * @version v1.0
 * @date 2020 -11-18 19:11:28
 */
public class HibernateValidatorUtils {

    /**
     * 开启快速结束模式 failFast (true)
     */
    private static Validator failFastValidator = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory().getValidator();

    /**
     * 全部校验
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


    private HibernateValidatorUtils() {
    }

    /**
     * 注解验证参数(快速失败模式)
     *
     * @param <T> the type parameter
     * @param obj the obj
     */
    public static <T> void fastFailValidate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = failFastValidator.validate(obj);
        //返回异常result
        if (constraintViolations.size() > 0) {
            String errorMessages = (constraintViolations.iterator().next().getPropertyPath().toString()
                    + ":" + constraintViolations.iterator().next().getMessage());
            throw new ExpoAppException(ExpoErrorCodeEnum.PARAM_ILLEGAL, errorMessages);
        }
    }

    /**
     * 注解验证参数(全部校验)
     *
     * @param <T> the type parameter
     * @param obj the obj
     */
    public static <T> void allCheckValidate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        //返回异常result
        if (constraintViolations.size() > 0) {
            StringBuilder errorMessages = new StringBuilder();
            for (ConstraintViolation<T> violation : constraintViolations) {
                errorMessages.append(String.format("%s:%s", violation.getPropertyPath().toString(), violation.getMessage()));
            }
            throw new ExpoAppException(ExpoErrorCodeEnum.PARAM_ILLEGAL, errorMessages.toString());
        }
    }
}
